fsp = require './fs-promises'
path = require 'path'
_ = require 'underscore'

Q = require 'q'

# string extension
String::startsWith ?= (s) -> @[...s.length] is s
String::endsWith   ?= (s) -> s is '' or @[-s.length..] is s


#root
# ┣components
# ┣models
# ┗templates
#
module.exports = (root, callback) ->

  fsp.traverse_safe path.resolve(root), relative: true
  .then (all) ->

    # 将所有文件转化为require语句
    console.log 'gen before'
    requires = _.map all, (each) ->

      each=each.replace /\\/g,"/"
      if each.endsWith('.html')
        return "require('text!./#{each}');"
      else if each.endsWith('.mustache')
        return "require('hgn!./#{each.replace('.mustache', '')}');"
      else if each.endsWith('.js')
        return "require('./#{each.replace('.js', '')}')"
      else if each.endsWith('.jsx') and each !='Panel.jsx' and each !='ComponentLibraryInspector.jsx'
          return "require('jsx!./#{each.replace('.jsx', '')}');"
      # body...

    # 所有的组件
    components = _.chain all
    .filter (each) ->
      each.startsWith('inspectors/')
    .map (each) ->
      {id: each.replace('inspectors/', '').replace('.jsx', '')}
    .value()

    # js = """
    # define(function(require) {
    #   #{requires.join(';\n\r')}
    #   return #{JSON.stringify(components)};
    # });
    # """
    js = """
      #{requires.join(';\n\r')}
    """

    callback(null, js)

  .catch (err) ->
    console.trace err
    callback(err)
